using System.Collections.Generic;
using Unity.Collections;
using UnityEngine;

namespace NewScene
{
    public class GameSpaceAssets
    {
        public static GameSpaceAssets Inst { get; private set; }

        public static void Init()
        {
            if (Inst != null)
                return;
            
            
        }

        public NativeList<SpaceAsset> Assets { get; private set; }
        public List<SpaceAssetRef> RefAssetsInSpace { get; private set; }
        public List<SpaceAssetDataRef> AssetsDataInSpace { get; private set; }

        public void RegisterAsset(int sceneObjKey, int assetId)
        {
            Assets.Add(new SpaceAsset
            {
                SceneObjKey = sceneObjKey,
                AssetObjKey = assetId
            });
        }

        private void InitializeSpaceBoxes()
        {
            for (int i = 0; i < SpaceBox.SpaceBoxEndX; i++)
            {
                for (int j = 0; j < SpaceBox.SpaceBoxEndZ; j++)
                {
                    var box = new SpaceBox
                    {
                        BoxId = i * SpaceBox.SpaceBoxEndX + j,
                        Bound = new Bounds(
                            new Vector3(i * SpaceBox.SpaceBoxSize + 25, 0, j * SpaceBox.SpaceBoxSize + 25),
                            new Vector3(SpaceBox.SpaceBoxSize, 100, SpaceBox.SpaceBoxSize)),
                        HasLoaded = false,
                        LodLevel = -1,
                        Weight = 0,
                        Lod0 = new NativeList<int>(Allocator.Persistent),
                        Lod1 = new NativeList<int>(Allocator.Persistent),
                        Lod2 = new NativeList<int>(Allocator.Persistent)
                    };
                    SpaceBoxManager.Inst.GameSpaceBoxes.Add(box);
                    SpaceBoxManager.Inst.GameSpaceBoxCenters.Add(new Vector2Int(i, j));
                }
            }
        }

        public void AssignToSpaceBox(int sceneObjKey, Vector3 position)
        {
            int i = (int)(position.x / SpaceBox.SpaceBoxSize);
            int j = (int)(position.z / SpaceBox.SpaceBoxSize);

            if (i >= SpaceBox.SpaceBoxStartX && i < SpaceBox.SpaceBoxEndX &&
                j >= SpaceBox.SpaceBoxStartZ && j < SpaceBox.SpaceBoxEndZ)
            {
                int idx = i * SpaceBox.SpaceBoxEndX + j;
                SpaceBoxManager.Inst.GameSpaceBoxes[idx].Lod0.Add(sceneObjKey); // 默认 LOD0
            }
        }
    }
}